//
//  UDRegViewController.swift
//  Chatter
//
//  Created by David on 16/7/13.
//  Copyright © 2016年 David. All rights reserved.
//  注册


import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
    switch (lhs, rhs) {
    case let (l?, r?):
        return l < r
    case (nil, _?):
        return true
    default:
        return false
    }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
    switch (lhs, rhs) {
    case let (l?, r?):
        return l > r
    default:
        return rhs < lhs
    }
}


@objc protocol UDLoginRegDelegate {
    @objc optional func doubleDismissRegView()
}

class UDRegViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate {
    
    let GOTO_LOGIN_ALERT_ID = 101
    
    fileprivate var tableView:UITableView!
    var navigationBar:UINavigationBar!
    
    fileprivate var emailTextField:UDTextField!
    fileprivate var passwordTextField:UDTextField!
    fileprivate var verifyTextField:UDTextField!
    //private var verifyImg:UIButton!
    fileprivate var registerBtn:UIButton!
    fileprivate var msg:UILabel!
    
    fileprivate var spinnerBG:UIView!
    
    var delegate: UDLoginRegDelegate?
    
    //register compare with login
    
    fileprivate var passwordConfirmTextField:UDTextField!
    fileprivate var getSmsCodeBtn: UIButton!
    
    fileprivate var sendSmsCountDown = 60
    
    // DEL: private var forgetPswBtn:UIButton!
    // DEL: requireVerify:Bool
    // DEL: func checkNeedVerify()
    
    /*
     @objc private func refreshVerifyImg(){
     NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.GET_VERIFY)")!), queue: NSOperationQueue(), completionHandler: { (resp:NSURLResponse?, returnData:NSData?, err:NSError?) in
     if err == nil{
     if let data = returnData{
     dispatch_async(dispatch_get_main_queue(), {
     self.verifyImg.setImage(UIImage(data: data), forState: .Normal)
     self.spinnerBG.alpha = 0
     })
     }
     }
     })
     }
     */
    
    override var preferredStatusBarStyle : UIStatusBarStyle {
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        self.modalTransitionStyle = .crossDissolve
        
        
        tableView = UITableView(frame: CGRect(x: 0, y: 64, width: self.view.frame.width, height: self.view.frame.height - 64), style: .grouped)
        tableView.keyboardDismissMode = .onDrag
        tableView.allowsSelection = false
        self.view.addSubview(tableView)
        
        msg = UILabel(frame: CGRect(x: 0, y: 40, width: self.view.frame.width, height: 24))
        msg.textAlignment = .center
        msg.font = UIFont.systemFont(ofSize: 12)
        
        msg.textColor = UIColor.brown
        msg.backgroundColor = UIColor.orange
        msg.alpha = 0
        msg.center.y = 52
        view.addSubview(msg)
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
//        navigationBar.barStyle = .black
//        navigationBar.barTintColor = Fatcat.THEME_COLOR
//        navigationBar.tintColor = UIColor.white
        let navItem = UINavigationItem(title: "注册")
        navigationBar.pushItem(navItem, animated: true)
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(UDRegViewController.dismissAll))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: .plain, target: self, action: #selector(UDRegViewController.gotoLogin))
        
        emailTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        emailTextField.boderWidth = 0
        emailTextField.placeholder = "用户名"
        emailTextField.keyboardType = .emailAddress
        emailTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        
        verifyTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 96, height: 32))
        verifyTextField.boderWidth = 0
        verifyTextField.textFieldType = .verify
        verifyTextField.placeholder = "手机验证码"
        verifyTextField.keyboardType = .numberPad
        verifyTextField.tabIndex = 1
        verifyTextField.returnKeyType = .next
        verifyTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        
        getSmsCodeBtn = UIButton(frame: CGRect(x: self.view.frame.width - 80, y: 0, width: 80, height: 48))
        getSmsCodeBtn.setTitle("获取验证码", for: UIControlState())
//        getSmsCodeBtn.setTitleColor(UIColor.black, for: UIControlState())
        getSmsCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        getSmsCodeBtn.backgroundColor = Fatcat.THEME_COLOR
        getSmsCodeBtn.addTarget(self, action: #selector(UDRegViewController.getSmsCode(_:)), for: .touchUpInside)
        
        passwordTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        passwordTextField.boderWidth = 0
        passwordTextField.textFieldType = .password
        passwordTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        passwordTextField.placeholder = "设置密码"
        passwordTextField.tabIndex = 2
        
        passwordConfirmTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        passwordConfirmTextField.boderWidth = 0
        passwordConfirmTextField.textFieldType = .password
        passwordConfirmTextField.tabIndex = 3
        passwordConfirmTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        passwordConfirmTextField.placeholder = "确认密码"
        passwordConfirmTextField.addTarget(self, action: #selector(UDRegViewController.scrollUpTextField(_:)), for: .editingDidBegin)
        
        /*
         verifyImg = UIButton(frame: CGRect(x: self.view.frame.width - 91.2, y: 24 + emailTextField.frame.height + 8 + passwordTextField.frame.height + 8 + passwordConfirmTextField.frame.height + 8 + verifyTextField.frame.height + 8, width: 83.2, height: 32))
         verifyImg.backgroundColor = UIColor.grayColor()
         verifyImg.contentMode = .ScaleToFill
         verifyImg.addTarget(self, action: #selector(UDRegViewController.refreshVerifyImg), forControlEvents: .TouchUpInside)
         */
        
        
        registerBtn = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 48))
        registerBtn.setTitle("注册", for: UIControlState())
//        registerBtn.backgroundColor = Fatcat.THEME_COLOR
//        registerBtn.setTitleColor(UIColor.white, for: UIControlState())
        registerBtn.addTarget(self, action: #selector(UDRegViewController.register), for: .touchUpInside)
        registerBtn.adjustsImageWhenDisabled = true
        
        
        spinnerBG = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinnerBG.center = view.center
        spinnerBG.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinnerBG.layer.cornerRadius = 5
        view.addSubview(spinnerBG)
        let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = CGPoint(x: 25, y: 25)
        spinner.activityIndicatorViewStyle = .white
        spinner.startAnimating()
        spinnerBG.addSubview(spinner)
        spinnerBG.alpha = 0
        //refreshVerifyImg()
        
        //        self.scrollView.addSubview(self.emailTextField)
        //        self.scrollView.addSubview(self.passwordTextField)
        //        self.scrollView.addSubview(self.passwordConfirmTextField)
        //        self.scrollView.addSubview(self.verifyTextField)
        //        self.scrollView.addSubview(self.verifyImg)
        //        self.scrollView.addSubview(self.registerBtn)
        //        self.scrollView.addSubview(self.msg)
        self.emailTextField.becomeFirstResponder()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(UDRegViewController.resendSmsTimer), userInfo: nil, repeats: true)
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 4
        }
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48
    }
    /*
     func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
     if section == 0{
     return 32
     }
     if section == 1{
     return 1
     }
     return 0
     }
     func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     if section == 0{
     return msg
     }
     return nil
     }
     */
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "row")
        if indexPath.section == 0{
            switch indexPath.row {
            case 0:
                cell.addSubview(emailTextField)
                break
            case 1:
                cell.addSubview(verifyTextField)
                cell.addSubview(getSmsCodeBtn)
                break
            case 2:
                cell.addSubview(passwordTextField)
                break
            case 3:
                cell.addSubview(passwordConfirmTextField)
                break
            default:
                break
            }
        }else if indexPath.section == 1 && indexPath.row == 0 {
            cell.addSubview(registerBtn)
        }
        return cell
    }
    
    @objc fileprivate func nextInput(_ sender: UDTextField){
        switch sender.tabIndex {
        case 0:
            verifyTextField.becomeFirstResponder()
            break
        case 1:
            passwordTextField.becomeFirstResponder()
            break
        case 2:
            passwordConfirmTextField.becomeFirstResponder()
            break
        case 3:
            register()
            break
        default:
            break
        }
    }
    
    func getSmsCode(_ sender: UIButton){
        if emailTextField.text == ""{
            setErrorMsg("请输入手机号码")
            emailTextField.becomeFirstResponder()
            return
        }
        if emailTextField.text?.characters.count != 11{
            setErrorMsg("手机号码不正确")
            emailTextField.becomeFirstResponder()
            return
        }else{
            
            if NSString(string: emailTextField.text!).substring(to: 1) != "1"{
                setErrorMsg("手机号码不正确")
                emailTextField.becomeFirstResponder()
                return
            }else{
                if Int64(emailTextField.text!) == nil {
                    setErrorMsg("手机号码不正确")
                    emailTextField.becomeFirstResponder()
                    return
                }
            }
        }
        setErrorMsg("")
        emailTextField.resignFirstResponder()
        
        var resq = URLRequest(url: URL(string: "\(serverURL)")!)
        resq.httpMethod = "POST"
        resq.httpBody = "data".data(using: String.Encoding.utf8)
        URLSession.shared.dataTask(with: resq, completionHandler: {(data:Data?, resp:URLResponse?, err:Error?) -> Void in
            var failed = true
            if err == nil {
                if data != nil {
                    
                    print(String(data: data!, encoding: String.Encoding.utf8))
                    let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
                    if jsonObj?.object(forKey: "code") != nil {
                        let reCode = jsonObj?.object(forKey: "code") as! Int
                        if reCode == 200 {
                            failed = false
                            DispatchQueue.main.async(execute: {
                                self.getSmsCodeBtn.isEnabled = false
                            })
                        }else if reCode == 202 {
                            failed = false
                            DispatchQueue.main.async(execute: {
                                let alert = UIAlertView(title: "用户已注册", message: nil, delegate: nil, cancelButtonTitle: "取消")
                                alert.tag = self.GOTO_LOGIN_ALERT_ID
                                alert.addButton(withTitle: "去登录")
                                alert.delegate = self
                                alert.show()
                            })
                        }
                    }
                }
            }
            if failed {
                DispatchQueue.main.async(execute: {
                    UIAlertView(title: "发送失败", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                })
            }
        }).resume()

        
    }
    
    @objc fileprivate func register(){
        if checkInput() {
            postRequest()
        }
    }
    
    
    fileprivate func checkInput() ->Bool{
        tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        if emailTextField.text == ""{
            setErrorMsg("请输入手机号码")
            emailTextField.becomeFirstResponder()
            
            return false
        }
        
        // MARK: 打开这段代码检查邮箱地址
        /*
         if emailTextField.text!.componentsSeparatedByString("@").count != 2{
         setErrorMsg("邮箱地址不正确")
         emailTextField.becomeFirstResponder()
         return false
         }
         */
        if emailTextField.text?.characters.count != 11{
            setErrorMsg("手机号码不正确")
            emailTextField.becomeFirstResponder()
            return false
        }else{
            if NSString(string: emailTextField.text!).substring(to: 1) != "1"{
                setErrorMsg("手机号码不正确")
                emailTextField.becomeFirstResponder()
                return false
            }else{
                if Int64(emailTextField.text!) == nil {
                    setErrorMsg("手机号码不正确")
                    emailTextField.becomeFirstResponder()
                    return false
                }
            }
        }
        
        
        
        if passwordTextField.text == ""{
            setErrorMsg("请输入密码")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        // MARK: 打开这段代码检查密码长度
        
        if passwordTextField.text?.characters.count < 6{
            setErrorMsg("密码长度不足")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        if passwordTextField.text?.characters.count > 16{
            setErrorMsg("密码长度太长")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        if passwordTextField.text != passwordConfirmTextField.text{
            setErrorMsg("两次密码不一致")
            passwordConfirmTextField.becomeFirstResponder()
            return false
        }
        
        if verifyTextField.text == ""{
            setErrorMsg("请输入验证码")
            verifyTextField.becomeFirstResponder()
            return false
        }else{
            if Int64(verifyTextField.text!) == nil {
                setErrorMsg("输入的验证码不合法")
                verifyTextField.becomeFirstResponder()
                return false
            }
        }
        setErrorMsg("")
        
        return true
    }
    
    fileprivate func postingStatus(_ status: Bool){
        
        emailTextField.isEnabled = !status
        passwordTextField.isEnabled = !status
        passwordConfirmTextField.isEnabled = !status
        verifyTextField.isEnabled = !status
        //verifyImg.enabled = !status
        registerBtn.isEnabled = !status
        if status{
            spinnerBG.alpha = 1
        }else{
            spinnerBG.alpha = 0
        }
    }
    
    fileprivate func postRequest(){
        postingStatus(true)
        var resq = URLRequest(url: URL(string: "\(serverURL)")!)
        resq.httpMethod = "POST"
        resq.httpBody = "post".data(using: String.Encoding.utf8)
        
        URLSession.shared.dataTask(with: resq, completionHandler: {(data:Data?, resp:URLResponse?, err:Error?) -> Void in
            if err == nil{
                if data != nil{
                    DispatchQueue.main.async(execute: {
                        self.handleResult(data!)
                    })
                    return
                }
            }
            DispatchQueue.main.async(execute: {
                self.setErrorMsg("网络错误")
                self.postingStatus(false)
            })
        }).resume()
        
    }
    
    fileprivate func handleResult(_ res: Data){
        print(String(data: res, encoding: String.Encoding.utf8))
        
        let jsonObj = try? JSONSerialization.jsonObject(with: res, options: .allowFragments) as! NSDictionary
        if jsonObj != nil{
            if jsonObj?.object(forKey: "code") != nil{
                let reCode = jsonObj?.object(forKey: "code") as! Int
                if reCode == 200 {
                    // MARK: 注册完成  保存登陆信息
                    UserDefaults.standard.set(emailTextField.text!, forKey: "user")
                    UserDefaults.standard.set(true, forKey: "orderListRefreshRequire")
                    let cookies = HTTPCookieStorage.shared.cookies!
                    let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
                    
                    UserDefaults.standard.set(cookiesData, forKey: "cookies")
                    UserDefaults.standard.synchronize()
                    dismiss(animated: false, completion: nil)
                    delegate?.doubleDismissRegView?()
                }else{
                    setErrorMsg(jsonObj?.object(forKey: "message") as! String)
                    postingStatus(false)
                }
                
                return
            }
        }
        setErrorMsg("json error")
        postingStatus(false)
        
    }
    
    fileprivate func setErrorMsg(_ message: String){
        msg.text = message
        if message != ""{
            if msg.alpha == 0{
                self.msg.alpha = 1
                UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {
                    
                    self.msg.center.y = 76
                }, completion: { (finished) in
                    UIView.animate(withDuration: 0.3, delay: 3, options: .curveLinear, animations: {
                        self.msg.center.y = 52
                    }, completion: { (finished1) in
                        self.msg.alpha = 0
                    })
                })
            }
            
        }
    }
    
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
        if alertView.tag == GOTO_LOGIN_ALERT_ID{
            if buttonIndex == 1{
                dismiss(animated: true, completion: nil)
            }
        }
    }
    
    @objc fileprivate func gotoLogin(){
        dismiss(animated: true, completion: nil)
        
    }
    func dismissAll(){
        dismiss(animated: false, completion: nil)
        delegate?.doubleDismissRegView?()
    }
    
    func resendSmsTimer(){
        if !getSmsCodeBtn.isEnabled {
            if sendSmsCountDown < 0{
                getSmsCodeBtn.setTitle("获取验证码", for: UIControlState())
                getSmsCodeBtn.isEnabled = true
                sendSmsCountDown = 60
                return
            }
            getSmsCodeBtn.setTitle("\(sendSmsCountDown)s", for: UIControlState())
            sendSmsCountDown -= 1
        }
        
    }
    
    func scrollUpTextField(_ sender:UITextField){
        print(tableView.contentOffset.y)
        if tableView.contentOffset.y <= 0 {
            tableView.setContentOffset(CGPoint(x: 0, y: 64), animated: true)
        }
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
